////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                            //
//                                                         WNProject                                                          //
//                                                                                                                            //
//            This file is distributed under the BSD 2-Clause open source license. See License.txt for details.               //
//                                                                                                                            //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include "WNNetworking/inc/WNWindowsINConnection.h"
#include "WNMemory/inc/WNManipulation.h"
#include "WNStrings/inc/WNStrings.h"

WNNetworking::WNWindowsINConnection::WNWindowsINConnection(WNNetworkManager& _manager):
    WNWindowsConnection(_manager){
}

WNNetworking::WNNetworkingError WNNetworking::WNWindowsINConnection::Initialize(SOCKET _listenSocket, WNNetworking::WNConnectedCallback _callback) {
    sockaddr_in address;
    int sockAddrSize = sizeof(address);
    WNMemory::WNMemClrT(&address);
    
    mSocket = accept(_listenSocket, (sockaddr*)&address, &sockAddrSize);
    if(INVALID_SOCKET == mSocket) {
        return(eWNCannotCreateSocket);
    }
    WN_SIZE_T length = WN_SNPRINTF(NULL,0, "%s:%d", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
    
    mConnectionName = WNMemory::WNMallocT<WN_CHAR>(length + 1);
    WN_SNPRINTF(mConnectionName,length+1, "%s:%d", inet_ntoa(address.sin_addr), ntohs(address.sin_port));

    mCallback = _callback;
    return(eWNOK);
}


WNNetworking::WNWindowsINConnection::~WNWindowsINConnection () {
    
}

WN_BOOL WNNetworking::WNWindowsINConnection::FireCallback() {
    return(mCallback.Execute(mConnectionName));
}
